﻿using Microsoft.Xna.Framework;
using System.Collections.Generic;
using Terraria;
using Terraria.Audio;
using Terraria.ID;
using Terraria.ModLoader;
using Terraria.UI;

namespace Bundlesone.Content.Items
{
    public class BundleUISystem : ModSystem
    {
        internal BundleUIState BundleUI;
        private UserInterface _bundleUserInterface;
        private bool _isUIOpen;
        private Bundle _currentBundle;
        public bool IsUIOpen => _isUIOpen;
        public override void Load()
        {
            BundleUI = new BundleUIState();
            BundleUI.Activate();
            _bundleUserInterface = new UserInterface();
            _bundleUserInterface.SetState(null);
        }

        public void ToggleBundleUI(Bundle bundle)
        {
            if (_isUIOpen && _currentBundle != null)
            {
                BundleUI.SaveItems();
            }

            _isUIOpen = !_isUIOpen;

            if (_isUIOpen)
            {
                _currentBundle = bundle;
                BundleUI.SetStorage(bundle.StoredItems);
                _bundleUserInterface.SetState(BundleUI);
                SoundEngine.PlaySound(SoundID.MenuOpen);
                Main.playerInventory = true;
            }
            else
            {
                _bundleUserInterface.SetState(null);
                SoundEngine.PlaySound(SoundID.MenuClose);
                _currentBundle = null;
            }
        }

        public override void UpdateUI(GameTime gameTime)
        {
            if (_isUIOpen)
            {
                _bundleUserInterface?.Update(gameTime);
            }
        }

        public override void ModifyInterfaceLayers(List<GameInterfaceLayer> layers)
        {
            int mouseTextIndex = layers.FindIndex(layer => layer.Name.Equals("Vanilla: Mouse Text"));
            if (mouseTextIndex != -1)
            {
                layers.Insert(mouseTextIndex, new LegacyGameInterfaceLayer(
                    "Bundles: Bundle UI",
                    delegate
                    {
                        if (_isUIOpen)
                            _bundleUserInterface.Draw(Main.spriteBatch, new GameTime());
                        return true;
                    },
                    InterfaceScaleType.UI)
                );
            }
        }
    }
}